﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CSM.Protocol;
using CSM.System.User;
using CSM.System.Route;

namespace CSMClient
{
	public partial class FormDownload : Form
	{
		UserToken token = new UserToken();

		public FormDownload()
		{
			SocketManager.DataInput += new ZYSocket.ClientA.DataOn(SocketManager_DataInput);
			InitializeComponent();
			this.Closed += new EventHandler(Download_Closed);
		}

        /// <summary>
        /// 输入包输入处理
        /// </summary>
        /// <param name="Data"></param>
		void SocketManager_DataInput(byte[] data)
		{
			ProtocolBase[] p = Protocol.Parser(data, ref token);
			if (p != null)
			{
				foreach (ProtocolBase item in p)
				{
					switch (item.Type)
					{
						case ProtocolWord.RequestUserInfoResponse:
							{
								RequestUserInfoResponse _resp = item as RequestUserInfoResponse;
								InitUserInfo(_resp);

								RequestSystemInfo temp = new RequestSystemInfo();
								SocketManager.client.SendTo(Protocol.Encoder(temp));
							}
							break;
						case ProtocolWord.RequestCompanysResponse:
							{
								RequestCompanysResponse _resp = item as RequestCompanysResponse;
								List<Company> comps = new List<Company>();

								for (int i = 0; i < _resp.IDs.Length; i++)
								{
									Company comp = new Company();
									comp.ID = _resp.IDs[i];
									comp.Name = _resp.Names[i];
									comps.Add(comp);
								}

								RouteSystem.Companys = comps.ToArray();
							}
							break;
						default:
							break;
					}
				}
			}
		}

		private void InitUserInfo(RequestUserInfoResponse _resp)
		{
			UserInfo ui = Program.userInfo;

			ui.id = _resp.id;
			ui.name = _resp.name;
			ui.isMale = _resp.isMale;
			ui.tel_num = _resp.tel_num;
			ui.work_no = _resp.work_no;
			ui.isFreeze = _resp.isFreeze;
			ui.isUnregist = _resp.isUnregist;
			ui.birthday = _resp.birthday;
			ui.email = _resp.email;
		}
		
		void Download_Closed(object sender, EventArgs e)
		{
			//删除数据包输入事件
			SocketManager.DataInput -= new ZYSocket.ClientA.DataOn(SocketManager_DataInput);
		}

		private void FormDownload_Shown(object sender, EventArgs e)
		{
			RequestUserInfo temp = new RequestUserInfo();

			SocketManager.client.SendTo(Protocol.Encoder(temp));
		}
	}
}
